import React, { useState, useRef } from 'react';
import { Card, Input, Button, Upload, message, Select, Row, Col } from 'antd';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';
import type { UploadProps } from 'antd';
import { InboxOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const { Dragger } = Upload;
const { Option } = Select;

const SceneSubstitution: React.FC = () => {
  const [description, setDescription] = useState<string>('');
  const [modelImageUrl, setModelImageUrl] = useState<string>('');
  const [sceneImageUrl, setSceneImageUrl] = useState<string>('');
  const [selectedSceneType, setSelectedSceneType] = useState<string>('indoor');
  const [loading, setLoading] = useState<boolean>(false);
  const [tourVisible, setTourVisible] = useState(false);
  
  // 使用HTML元素的ref引用方式
  const modelUploadRef = useRef<HTMLDivElement>(null);
  const sceneUploadRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const sceneTypeRef = useRef<HTMLDivElement>(null);
  const generateRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  
  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };
  
  // 定义steps配置
  const tourSteps = [
    {
      key: 'modelUpload',
      title: '上传模特图片',
      description: '上传包含模特的照片，这是场景替换的基础图片',
    },
    {
      key: 'sceneUpload',
      title: '上传参考场景图片（可选）',
      description: '上传一张场景参考图片，帮助AI更好地理解您想要的场景风格',
    },
    {
      key: 'description',
      title: '添加场景描述',
      description: '详细描述您想要的场景效果，如：时尚工作室、户外自然环境、城市街头等',
    },
    {
      key: 'sceneType',
      title: '选择场景类型',
      description: '从预设的场景类型中选择一个，帮助AI更精准地生成场景',
    },
    {
      key: 'generate',
      title: '生成场景替换图片',
      description: '完成所有配置后，点击此按钮开始生成场景替换图片',
    },
    {
      key: 'result',
      title: '查看生成结果',
      description: '生成成功后，您可以在此处查看、下载或重新生成场景替换图片',
    },
  ];

  // 组织ref引用
  const tourRefs = {
    modelUpload: modelUploadRef,
    sceneUpload: sceneUploadRef,
    description: descriptionRef,
    sceneType: sceneTypeRef,
    generate: generateRef,
    result: resultRef,
  };

  const modelUploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    action: '/api/upload',
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 模特图片上传成功`);
        setModelImageUrl(URL.createObjectURL(info.file.originFileObj as File));
      } else if (status === 'error') {
        message.error(`${info.file.name} 模特图片上传失败`);
      }
    },
    onDrop(e) {
      console.log('Dropped model files', e.dataTransfer.files);
    },
  };

  const sceneUploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    action: '/api/upload',
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 场景图片上传成功`);
        setSceneImageUrl(URL.createObjectURL(info.file.originFileObj as File));
      } else if (status === 'error') {
        message.error(`${info.file.name} 场景图片上传失败`);
      }
    },
    onDrop(e) {
      console.log('Dropped scene files', e.dataTransfer.files);
    },
  };

  const handleGenerate = () => {
    if (!description || !modelImageUrl) {
      message.warning('请填写描述并上传模特图片');
      return;
    }

    setLoading(true);
    // 模拟AI生成过程
    setTimeout(() => {
      message.success('场景替换图片生成成功');
      setLoading(false);
    }, 3000);
  };

  return (
    <>
      <div className="p-4">
        <h2 className="text-xl font-bold mb-4" style={{ display: 'flex', alignItems: 'center' }}>
          场景替换
          <TourGuideButton onClick={showTour} />
        </h2>
      <Row gutter={[16, 16]}>
        <Col span={24} md={12}>
          <Card title="上传模特图片" className="h-full">
            <div ref={modelUploadRef}>
              <Dragger {...modelUploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持单个图片文件上传，包含模特的照片
              </p>
            </Dragger>
            </div>
            </Card>
        </Col>
        <Col span={24} md={12}>
          <Card title="上传参考场景图片 (可选)" className="h-full">
            <div ref={sceneUploadRef}>
              <Dragger {...sceneUploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持单个图片文件上传，作为场景参考
              </p>
            </Dragger>
            </div>
            </Card>
        </Col>
        <Col span={24}>
          <Card title="生成参数" className="h-full">
            <Row gutter={[16, 16]}>
              <Col span={24} md={16}>
                <div ref={descriptionRef}>
                  <TextArea
                    rows={4}
                    placeholder="请描述您想要的场景效果，如：时尚工作室、户外自然环境、城市街头等"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                  />
                </div>
              </Col>
              <Col span={24} md={8}>
                <div className="mb-4" ref={sceneTypeRef}>
                  <label className="block mb-2">场景类型:</label>
                  <Select
                    value={selectedSceneType}
                    onChange={setSelectedSceneType}
                    style={{ width: '100%' }}
                  >
                    <Option value="indoor">室内场景</Option>
                    <Option value="outdoor">户外场景</Option>
                    <Option value="studio">摄影棚</Option>
                    <Option value="casual">休闲环境</Option>
                    <Option value="fashion">时尚场景</Option>
                  </Select>
                </div>
                <div ref={generateRef}>
                  <Button type="primary" style={{ marginTop: '16px' }} onClick={handleGenerate} loading={loading} block>
                    生成场景替换图片
                  </Button>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>
      {modelImageUrl && (
        <Card title="生成结果" className="mt-4">
          <div className="flex justify-center" ref={resultRef}>
            <img src={modelImageUrl} alt="场景替换结果" className="max-w-full max-h-[500px]" style={{ 
                maxWidth: '100vw', 
                maxHeight: '60vh',
                margin: '0 auto'
              }} />
          </div>
          <div className="flex justify-center mt-4">
            <Button className="mr-2">下载图片</Button>
            <Button type="primary">重新生成</Button>
          </div>
        </Card>
      )}
    </div>
    
    <CommonTour
      open={tourVisible}
      onClose={() => setTourVisible(false)}
      steps={tourSteps}
      targetRefs={tourRefs}
    />
    </>
  );
};

export default SceneSubstitution;